<?php
class Zhetaoke{
    private $union;
    private $data = [];
    public function __construct($union)
    {
        $this->union = $union;
    }

    /**
     *
     * 已付款：指订单已付款，但还未确认收货
     * 已收货：指订单已确认收货，但商家佣金未支付
     * 已结算：指订单已确认收货，且商家佣金已支付成功
     * 已失效：指订单关闭/订单佣金小于0.01元，订单关闭主要有： * 1）买家超时未付款； * 2）买家付款前，买家/卖家取消了订单； * 3）订单付款后发起售中退款成功；
     * 3：订单结算，
     * 12：订单付款，
     * 13：订单失效，
     * 14：订单成功
    //0	默認 1	待支付 2	已支付 3	已退款 4	已完成 5	已失效 6	已結算 11	已取消
    //3：訂單結算， 12：訂單付款， 13：訂單失效， 14：訂單成功
     */
    public $status = [
        12 => 2,
        13 => 11,
        14 => 2,
        3 => 6,
    ];

	//公共查询
	public function public_query($url,$params = []){
		$key=["appkey"=>$this->union['ztkAppKey']];
		$url=$url.'?'.http_build_query(array_merge($key,$params));
		$request_result = file_get_contents($url);
		return json_decode($request_result,true);
	}
	//公共列表转换
	public function trun_list($res,$code=0){
		$data=[];
		$site="haodanku";
		foreach($res as $k =>$v){
			$arr=[
				"GoodsId"=>$v['tao_id'],
				"Title"=>$v['tao_title'],
				"ShortTitle"=>$v['title'],
				"ShopType"=>$v["user_type"]== "1"?"天猫":"淘宝",
				"PicLogo"=>$v['pict_url'],
				"CouponMoney"=>$v['coupon_info_money'],
				"CouponSurplus"=>$v['coupon_remain_count'],
				"Price"=>$v['size'],
				"EndPrice"=>$v['quanhou_jiage'],
				"Commission"=>$v['tkfee3'],
				"MonthSale"=>$v['volume'],
				"Site"=>$site,
                "ItemFrom"=>'zhetaoke',
			];
				//多余的
			if($code ==1){
				$arr1=[
				'PicList'=>$v['pcDescContent'] ? explode("|",str_replace("//","http://",$v['pcDescContent'])) : [],
				'SmallImages'=>explode("|",$v['small_images']),            'VideoUrl'=>'http://video.haodanku.com/58016264efff9da9f0df352333c3a1b5.mp4?attname=1568892294.mp4', //empty($v['zhibo_url']),
				"ShopName"=>$v['shop_title'],            "ShopId"=>$v['seller_id'],
				"ShopUrl"=>'http://store.taobao.com/shop/view_shop.htm?user_number_id='.$v['seller_id'],
				"ShopIcon"=>$v['shopIcon'],            "DescTxt"=>sprintf("%.2f",round(4.9,2)),
				"ServTxt"=>sprintf("%.2f",round(4.9,2)),                         
				"AvgTxt"=>sprintf("%.2f",round(4.9,2)),];
			}
			$data[]=$arr;
		}
		return $data;
	}


	public function you_also_like($params){
		$url="https://api.zhetaoke.com:10001/api/open_item_guess_like.ashx";
		$param = [
			'page'=>isset($params['page'])?$params['page']:1,
			'page_size'=>isset($params['page_size'])?$params['page_size']:1,
			'sort'=>'new',
			'device_encrypt'=>'MD5',
			'device_type'=>'IMEI',
			'device_value'=>md5($params['IMEI']),
			        ]; 
		if($params['source'] == 'ios'){
		$params['device_type']='IDFA';
		}
		$res=$this->public_query($url,$param);
		if($res['status'] == 200){
			return $this->trun_list($res['content'],$code=0);
		}
		return $res;
			
	}



    /**
     *
     * 订单处理
     */
    private function returnOrderDeal($data)
    {
        $responseTurnData = [];
        foreach ($data as $k => $v) {
            if (!isset($v['relation_id'])) {
                $v['rid'] = 0;
            }

            $order_status = $this->status[$v['tk_status']];

            $item_price = 0;
            if (isset($v['item_price'])) {
                $item_price = $v['item_price'];
            } else {
                if (isset($v['alipay_total_price'])) {
                    $item_price = $v['alipay_total_price'];
                }
            }

            $orderType = in_array($order_status,[2,4,6]) ? 1 : 4;

            $turnData = [
                'orderId' => $v['trade_id'],
                'orderStatus' => $order_status,
                'site' =>'haodanku',
                'orderSrc' => $v['order_type'] == '饿了么' ? 6 : 1,
                'tag' => '淘宝',
                'tagItem' => $v['order_type'],
                'name' => $v['item_title'],
                'goodsId' => isset($v['item_id']) ? $v['item_id'] : '',
                'images' => $v['item_img'],
                'rid' => isset($v['relation_id']) && !empty($v['relation_id']) ? $v['relation_id'] : 0,
                'shopName' => $v['seller_nick'],
                'price' => $item_price,
                'orderType' => $v['refund_tag'] == 1 ? 2 : $orderType,
                'payMoney' => isset($v['alipay_total_price']) && !empty($v['alipay_total_price']) ? $v['alipay_total_price'] : 0,
                'rebateAmount' => doubleval($v['pub_share_fee']) > 0 ? $v['pub_share_fee'] : $v['pub_share_pre_fee'],
                'incomeRate' => $v['total_commission_rate'] ? $v['total_commission_rate'] : $v['income_rate'],
                'orderCreateTime' => $v['tk_create_time'],
                'orderPaidTime' => isset($v['tk_paid_time']) ? $v['tk_paid_time'] : null,
                'orderEarningTime' => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
                'settleTime' => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
            ];
            $responseTurnData[] = $turnData;
        }
        return $responseTurnData;
    }



    /**
     * 拉取订单
     * https://open.taobao.com/api.htm?docId=43755&docType=2&scopeId=16322
     * http://www.zhetaoke.com/user/open/open_dingdanchaxun2.aspx
     * @param $start_time    订单查询开始时间
     * @param $end_time        订单查询结束时间
     * @param string $position_index 位点，除第一页之外，都需要传递；前端原样返回。注意：从第二页开始，位点必须传递前一页返回的值，否则翻页无效。
     * @param int $page_no 第几页
     * @param int $up 标识 场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
     * @return array
     */
    public function getOrder($start_time, $end_time, $position_index = '', $page_no = 1, $up = 0,&$responseMsgDataResult=[])
    {
//        $start_time="2022-07-20 10:00:24";
//        $end_time = "2022-07-20 11:49:24";
        $url = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx";
        $temp = [
            'appkey'=>$this->union['ztkAppKey'],
            'sid' => $this->union['ztkSid'],
            'start_time' => $start_time,
            'end_time' => $end_time,
            'order_scene' => $up ? 1 : 2,
            'position_index' => $position_index,
            'page_size' => 100,
            'page_no' => $page_no,
        ];
        $url    = $url . '?' . http_build_query($temp);
        $responseUrl    = json_decode(file_get_contents($url), true);
        if(!isset($responseUrl['url']) || empty($responseUrl['url'])){
            return [];
        }
        $responseMsg = json_decode(file_get_contents($responseUrl['url']), true);
        if(isset($responseMsg['error_response'])){
//            var_dump($responseMsg['error_response']['sub_msg']);
            return [];
        }
        if(!isset($responseMsg['tbk_sc_order_details_get_response']['data'])){
            return [];
        }
        $responseMsgData = $responseMsg['tbk_sc_order_details_get_response']['data'];
        if ($responseMsgData['results'] == [] && $responseMsgDataResult) {
            return [];
        }
        if ($responseMsgData['results'] != []) {
            if ($responseMsgDataResult == []) {
                $responseMsgDataResult = $responseMsgData['results']['publisher_order_dto'];
            } else {
                $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsgData['results']['publisher_order_dto']);
            }
        }

        if ($responseMsgData['has_next']) {
            $this->getOrder($start_time, $end_time, $responseMsgData['position_index'], $responseMsgData['page_no'] + 1, $up,$responseMsgDataResult);
        }

//        $write       = json_encode($responseMsgDataResult);
//        $write .= "-------------------------------------------------------------------------------------";
//        $create_file = BASE_PATH."/runtime/taobao.log";       //创建文件
//        file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);

        return $this->returnOrderDeal($responseMsgDataResult);
    }



    /*
     * http://www.zhetaoke.com/user/extend/extend_lingquan_tmall.aspx
     * 商品列表
     */
    public function goods_list($params)
    {
        $h_params = [];
        if (isset($params['category_id'])) {
            $h_params['cid'] = $params['category_id'];
        };
        if (isset($params['page_size']) && $params['page_size']) {
            $h_params['page_size'] = $params['page_size'];
        } else {
            $h_params['page_size'] = 10;
        }
        if (isset($params['page']) && $params['page']) {
            $h_params['page'] = $params['page'];
        } else {
            $h_params['page'] = 1;
        }
        if (!empty($params['order_by'])) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sort'] = "price_asc";
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sort'] = "price_desc";
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'desc') {
                $h_params['sort'] = "sale_num_asc";
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'asc') {
                $h_params['sort'] = "sale_num_desc";
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'desc') {
                $h_params['sort'] = "commission_rate_asc";
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'asc') {
                $h_params['sort'] = "commission_rate_desc";
            }
        } else {
            $h_params['sort'] = "new";
        }

        $h_params['appkey'] = $this->union['ztkAppKey'];

        $url    = "https://api.zhetaoke.com:10001/api/api_all.ashx";
        $url=$url.'?'.http_build_query($h_params);
        $responseMsg= json_decode(file_get_contents($url),true);
        if($responseMsg['status'] == '200'){
            $res = $this->trun_list($responseMsg['content']);
            return ['status'=>true,'data'=>$res,'msg'=>'获取成功'];
        }else{
            return ['status'=>false,'msg'=>'获取失败'];
        }
    }



    //折淘客的商品详情
    public function goods_detail($goods_id)
    {
        $url    = "https://api.zhetaoke.com:10002/api/api_detail.ashx";
        $params = [
            'tao_id' => $goods_id,
            'appkey' => $this->union['ztkAppKey']
        ];
        $url    = $url . '?' . http_build_query($params);
        $res    = json_decode(file_get_contents($url), true);
        if ($res['status'] != 200) {
            return ['status'=>false,'msg'=>$res['content']];
        }
        $res  = $res['content'][0];
        $site = 'haodanku';
        $arr  = [
            "GoodsId"         => $res['tao_id'],
            "Title"           => $res['tao_title'],
            "ShortTitle"      => $res['title'],
            "Suggest"         => $res['jianjie'],
            "ShopType"        => $res["user_type"] == "1" ? "天猫" : "淘宝",
            "PicLogo"         => $res['pict_url'],
            "CouponMoney"     => $res['coupon_info_money'],
            "CouponSurplus"   => $res['coupon_remain_count'],
            "Price"           => $res['size'],
            "EndPrice"        => $res['quanhou_jiage'],
            "Commission"      => $res['tkfee3'],
            "MonthSale"       => $res['volume'],
            "Site"            => $site,
            'Couponurl'       => '',
            'CouponStartTime' => $res['coupon_start_time'],
            'CouponEndTime'   => $res['coupon_end_time'],
            'PicList'         => $res['pcDescContent'] ? explode("|", str_replace("//", "http://", $res['pcDescContent'])) : [],
            'SmallImages'     => explode("|", $res['small_images']),
            'VideoUrl'        => empty($res['zhibo_url']) ? $res['zhibo_url'] : '',//'http://video.haodanku.com/58016264efff9da9f0df352333c3a1b5.mp4?attname=1568892294.mp4', //empty($res['zhibo_url']),
            "ShopName"        => $res['shop_title'],
            "ShopId"          => $res['seller_id'],
            "ShopUrl"         => 'http://store.taobao.com/shop/view_shop.htm?user_number_id=' . $res['seller_id'],
            "ShopIcon"        => $res['shopIcon'],
            "DescTxt"         => sprintf("%.2f", round(4.9, 2)),
            "ServTxt"         => sprintf("%.2f", round(4.9, 2)),
            "AvgTxt"          => sprintf("%.2f", round(4.9, 2)),
        ];
        return ['status'=>true,'msg'=>'获取成功','data'=>$arr];
    }




    /**
     * @param $res 获取店铺的名称
     * @param $res 店铺数组
     * @return mixed
     */
    public function shop_name($res){
        $item = array_column($res,'GoodsId');
        //返回第三方折淘客的店铺数据 itemid为淘宝商品ids，以,分割
        $items = implode(',',$item);
        $response = $this->goods_detail($items);
        foreach($res as $key=>$value){
            $res[$key]['ShopName'] = isset($response[$value['GoodsId']]['ShopName']) ? $response[$value['GoodsId']]['ShopName'] : '没有获取到店铺信息';
        }
        return $res;
    }


    /**
     * 淘口令解析商品
     * http://www.zhetaoke.com/user/open/open_shangpin_id.aspx
     */
    public function open_shangpin($word){
        $url="https://api.zhetaoke.com:10001/api/open_shangpin_id.ashx";
        $params=[
            'sid'=>$this->union['ztkSid'],
            'appkey'=>$this->union['ztkAppKey'],
            'content'=>$word,
            'type'=>1,
        ];
        $url=$url.'?'.http_build_query($params);
        $responseMsg= json_decode(file_get_contents($url),true);
        $responseResult = ['status'=>false,'msg'=>'解析不成功','data'=>[]];
        if(isset($responseMsg['item_id']) && !empty($responseMsg['item_id'])){
            $responseResult['status'] = true;
            $responseResult['msg'] = "解析成功";
            $responseResult['goodsId'] = $responseMsg['item_id'];
        }else{
            $responseResult['status'] = false;
            $responseResult['msg'] = isset($responseMsg['content']) ? $responseMsg['content'] : '解析不成功';
        }
        return $responseResult;
    }


    /**
     * 海淘商品API
     */
    public function haitao($params){
        $url = 'https://api.zhetaoke.com:10001/api/api_all.ashx';
        $h_params=[];
        if($params['page_size']){
            $h_params['pageSize']=$params['page_size'];
        }else{
            $h_params['pageSize']=10;
        }
        if($params['page']){
            $h_params['pageId']=$params['page'];
        }else{
            $h_params['pageId']=1;
        }
        if($params['cid']){
            $h_params['cid']=$params['cid'];
        }

        if($params['order_by']){
            if($params['order_by'] == 'price' && $params['sort'] == 'asc'){
                $h_params['sort']='price_asc';
            }
            if($params['order_by'] == 'price' && $params['sort'] == 'desc'){
                $h_params['sort']='price_desc';
            }
            if($params['order_by'] == 'sale' && $params['sort'] == 'asc'){
                $h_params['sort'] = 'sale_num_asc';
            }
            if($params['order_by'] == 'sale' && $params['sort'] == 'asc'){
                $h_params['sort'] = 'sale_num_desc';
            }
            if($params['order_by'] == 'commission' && $params['sort'] == 'asc'){
                $h_params['sort']='commission_rate_asc';
            }
            if($params['order_by'] == 'commission' && $params['sort'] == 'desc'){
                $h_params['sort']='commission_rate_desc';
            }
            if($params['order_by'] == 'moren' && $params['sort'] == 'desc'){
                $h_params['sort']=0;
            }
            if($params['order_by'] == 'new' && $params['sort'] == 'desc'){
                $h_params['sort']='new';
            }
        };
        $param=[
            'appkey'=>$this->union['ztkAppKey'],
        ];
        $param = array_merge($param,$h_params);
        $url=$url.'?'.http_build_query($param);
        $res= json_decode(file_get_contents($url),true);
        if($res['status'] == 200){
            $res = $this->trun_list($res['content']);
            return ['code'=>true,'data'=>$res];
        }else{
            return ['code'=>false,'data'=>$res['content']];
        }
    }


    //折淘客天猫商店
    public function tanmao_supermaket($params){
        $url = 'https://api.zhetaoke.com:10001/api/api_all.ashx';
        $h_params=[];
        if($params['page_size']){
            $h_params['page_size']=$params['page_size'];
        }else{
            $h_params['page_size']=10;
        }
        if($params['page']){
            $h_params['page']=$params['page'];
        }else{
            $h_params['page']=1;
        }

        if(empty($params['cid'])){
            $h_params['cid']=0;
        }else{
            $h_params['cid']=(int)$params['cid'];
        }

        if($params['order_by']){
            if($params['order_by'] == 'price' && $params['sort'] == 'asc'){
                $h_params['sort']='price_asc';
            }
            if($params['order_by'] == 'price' && $params['sort'] == 'desc'){
                $h_params['sort']='price_desc';
            }
            if($params['order_by'] == 'sale' && $params['sort'] == 'asc'){
                $h_params['sort'] = 'sale_num_asc';
            }
            if($params['order_by'] == 'sale' && $params['sort'] == 'asc'){
                $h_params['sort'] = 'sale_num_desc';
            }
            if($params['order_by'] == 'commission' && $params['sort'] == 'asc'){
                $h_params['sort']='commission_rate_asc';
            }
            if($params['order_by'] == 'commission' && $params['sort'] == 'desc'){
                $h_params['sort']='commission_rate_desc';
            }
            if($params['order_by'] == 'new' && $params['sort'] == 'desc'){
                $h_params['sort']='new';
            }
            if($params['order_by'] == 'totalSale' && $params['sort'] == 'asc'){     //总销量
                $h_params['sort']='total_sale_num_asc';
            }
            if($params['order_by'] == 'totalSale' && $params['sort'] == 'desc'){
                $h_params['sort']='total_sale_num_desc';
            }
            if($params['order_by'] == 'tkfee' && $params['sort'] == 'asc'){     //按照返佣金额
                $h_params['sort']='tkfee_asc';
            }
            if($params['order_by'] == 'tkfee' && $params['sort'] == 'desc'){
                $h_params['sort']='tkfee_desc';
            }
            if($params['order_by'] == 'coupon' && $params['sort'] == 'asc'){     //按照返佣金额
                $h_params['sort']='coupon_info_money_asc';
            }
            if($params['order_by'] == 'coupon' && $params['sort'] == 'desc'){
                $h_params['sort']='coupon_info_money_desc';
            }
        };
        $param=[
            'appkey'=>$this->union['ztkAppKey'],
        ];
        $param = array_merge($param,$h_params);
        $url=$url.'?'.http_build_query($param);
        $res= json_decode(file_get_contents($url),true);
        if($res['status'] == 200){
            $res = $this->trun_list($res['content']);
            return ['code'=>true,'data'=>$res];
        }else{
            return ['code'=>false,'data'=>$res['content']];
        }
    }



    public function get_add_order($start_time, $end_time, $position_index = '', $page_no = 1, $up = 0)
    {
        $url  = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx";
        $temp = [
            'sid'        => $this->union['ztkSid'],
            'start_time' => $start_time,
            'end_time'   => $end_time,
            'order_scene'   => 2,
            'position_index' => $position_index,
            'page_size'      => 100,
            'page_no'        => $page_no,
        ];
        $res  = $this->public_query($url, $temp);
        $data = json_decode(file_get_contents($res['url']), true);
        //访问服务
        $res    = $data['tbk_sc_order_details_get_response']['data'];
        if ($res['results'] == [] && $this->data == []) {
            return [];
            //echo 111;die;
        }

        if ($res['results'] != []) {
            if ($this->data == []) {
                $this->data = $res['results']['publisher_order_dto'];
            } else {
                $this->data = array_merge($this->data, $res['results']['publisher_order_dto']);
            }
        }

        if ($res['has_next']) {
            $this->get_add_order($start_time, $end_time, $res['position_index'], $res['page_no'] + 1, $up);
        }
        return $this->data;
    }




    /**
     * 折淘客聚划算
     */
    public function api_all_juhuasuan($params){
        $h_params=[];
        if($params['type'] == 4){
            $h_params['jt'] = "juhuasuan";
        }elseif ($params['type'] == 1){
            $h_params['jt'] = "taoqianggou";
        }else{
            $h_params['jt'] = "";
        }
        $h_params['cid'] = (isset($params['cid']) && !empty($params['cid'])) ? $params['cid'] : "";
        $h_params['page'] = (isset($params['page']) && !empty($params['page'])) ? (int)$params['page'] : 1;
        $h_params['page_size'] = (isset($params['page_size']) && !empty($params['page_size'])) ? (int)$params['page_size'] : 10;
        $h_params['sort'] = "commission_rate_desc";
        $h_params['appkey'] = $this->union['ztkAppKey'];
        $url="https://api.zhetaoke.com:10001/api/api_all.ashx";
        $data  = $this->public_query($url, $h_params);
        if($data['status'] != 200){
            return ['code'=>0,'msg'=>"没有获取到数据"];
        }else{
            $data = $this->trun_list($data['content']);
            return ['code'=>1,'data'=>$data,'min_id'=>$h_params['page']+1,'msg'=>'获取数据成功'];
        }
    }



    /**
     * @param $tb_rid  淘宝授权码
     * @param $goods_id 商品id
     * @param $source 空的代表android 来源
     * @return array
     */
    public function taobao_turn($tb_rid, $goods_id, $source = 'android', $tb_special_id = '')
    {
        $h_params['appkey'] = $this->union['ztkAppKey'];
        $h_params['sid'] = $this->union['ztkSid'];
        if($source == 'ios'){
            $h_params['pid'] = $this->union['iosPid'];
        }else{
            $h_params['pid'] = $this->union['androidPid'];
        }
        $h_params['num_iid'] = $goods_id;
        $h_params['relation_id'] = $tb_rid;
        $h_params['special_id'] = $tb_special_id;
        $h_params['signurl'] = 5;
        $url="https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian.ashx";
        $data  = $this->public_query($url, $h_params);
        if($data['status'] != 200){
            return ['status'=>false,'msg'=>"转链失败"];
        }else{
            if(!isset($data['content'][0])){
                return ['status'=>false,'msg'=>"转链失败"];
            }
            $responseMsg = $data['content'][0];
            $responseResult['url'] = isset($responseMsg['item_url']) && !empty($responseMsg['item_url']) ? $responseMsg['item_url']: '';
            $responseResult['short_url'] = isset($responseMsg['shorturl']) && !empty($responseMsg['shorturl']) ? $responseMsg['shorturl']: '';
            $responseResult['long_url'] = isset($responseMsg['coupon_click_url']) && !empty($responseMsg['coupon_click_url']) ? $responseMsg['coupon_click_url']: '';
            $responseResult['app_url'] = isset($responseMsg['coupon_click_url']) && !empty($responseMsg['coupon_click_url']) ? $responseMsg['coupon_click_url']: '';
            $responseResult['min_commission'] = isset($responseMsg['min_commission_rate']) && !empty($responseMsg['min_commission_rate']) ? $responseMsg['min_commission_rate'] : '';
            return ['status' => true, 'msg' => '获取成功', 'data' => $responseResult];
        }
    }


    /**
     * 聚划算
     * http://www.zhetaoke.com/user/extend/extend_lingquan_juhuasuan.aspx
     */




}
